package com.joint.web.action.com;
import com.fz.us.base.bean.BaseEnum;
import com.fz.us.base.bean.Pager;
import com.google.common.collect.Sets;
import com.joint.base.bean.FlowEnum;
import com.joint.base.entity.Company;
import com.joint.base.entity.FileManage;
import com.joint.base.entity.Users;
import com.joint.base.exception.users.DutyNotExistsException;
import com.joint.base.exception.workflow.PcfgNotExistException;
import com.joint.base.util.DataUtil;
import com.joint.core.entity.Employees;
import com.joint.core.entity.Employment;
import com.joint.core.entity.Interview;
import com.joint.core.entity.Records;
import com.joint.core.service.EmployeesService;
import com.joint.core.service.EmploymentService;
import com.joint.core.service.RecordsService;
import com.joint.web.action.BaseFlowAction;
import net.sf.json.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.apache.struts2.convention.annotation.ParentPackage;

import javax.annotation.Resource;
import java.util.*;

/**
 * Created by dqf on 2015/8/26.
 */
@ParentPackage("com")
public class AjaxRecordsAction extends BaseFlowAction {
    
    
    @Resource
    private RecordsService recordsService;
    @Resource
    private EmployeesService employeesService;

    private Employment employment;
    private Employees employees;
    private Records records;
    private Users loginUser;
    private String creater;
    private String createDate;

    /**
     * 奖惩类型
     */
    private String types;

    /**
     * 奖惩时间
     */
    private Date rpDate;

    /**
     * 相关附件
     */
    private String accessoriesText;
    private String accessoriesFileId;
    private String accessoriesId;

    private String name;

    /**
     * 项目视图
     * @return
     */
    public String execute(){
        return "records";
    }

    /**
     * 列表
     */
    public String list(){
        pager = new Pager();
        if (rows <= 0){
            rows = 10;
        }
        pager.setPageSize(rows);
        pager.setPageNumber(page);
        pager.setOrderBy("createDate");
        pager.setOrderType(BaseEnum.OrderType.desc);

        if(StringUtils.isNotEmpty(sidx)&& BaseEnum.OrderType.valueOf(sord)!=null){
            pager.setOrderBy(sidx);
            pager.setOrderType(BaseEnum.OrderType.valueOf(sord));
        }
        Company com = usersService.getCompanyByUser();
        Users user = usersService.getLoginInfo();

        Map<String,Object> params = new HashMap<String,Object>();
        params = getSearchFilterParams(_search,params,filters);
        //内嵌视图
        if (StringUtils.isNotEmpty(parentId)){
            employees= employeesService.get(parentId);
            params.put("employees",employees);

        }
        params.put("company",com);
        params.put("state",BaseEnum.StateEnum.Enable);
       
        //所有单子
        params.put("processState", new FlowEnum.ProcessState []{FlowEnum.ProcessState.Running, FlowEnum.ProcessState.Backed, FlowEnum.ProcessState.Finished, FlowEnum.ProcessState.Deny});
        pager=recordsService.findByPagerAndLimit(true, "records", pager, params);

        List<Records> recordsList;
        if (pager.getTotalCount() > 0){
            recordsList = (List<Records>) pager.getList();
        }else{
            recordsList = new ArrayList<>();
        }

        List<JSONObject> dataRows=new ArrayList<JSONObject>();
        Map<String, Object> data = new HashMap<String, Object>();
        Map<String,Object> rMap;

        for(Records records :recordsList){
            rMap = new HashMap<String,Object>();
            rMap.put("id",records.getId());
            rMap.put("name",records.getName());
            String types = records.getTypes();

            if(types.equals("0")){
                rMap.put("types","奖励");
            } else{
                rMap.put("types","惩罚");
            }
            rMap.put("time", DataUtil.DateToString(records.getRpDate(),"yyyy-MM-dd"));
            rMap.put("state",records.getProcessState().value());
            JSONObject o = JSONObject.fromObject(rMap);
            dataRows.add(o);
        }

        data.put("dataRows",dataRows);
        data.put("page",page);
        data.put("rows",rows);

        long recordsNum = pager.getTotalCount();
        data.put("total",calcPageNum(recordsNum));
        data.put("records",recordsNum);

        return  ajaxJson(JSONObject.fromObject(data).toString());
    }

    /**
     * 查看
     * @return
     */
    public String read(){

        accessoriesFileId="";
        loginUser = usersService.getLoginInfo();
        creater=loginUser.getName();
        if(StringUtils.isNotEmpty(keyId)) {
            records = recordsService.get(keyId);
            numStatus = workflowService.getNumStatus(keyId, loginUser);
            createDate= DataUtil.DateToString(records.getCreateDate(),"yyyy-MM-dd");
            if(records.getAccessories().size()>0){
                for(FileManage r:records.getAccessories()){
                    accessoriesFileId+=r.getId()+",";
                }
            }
        }
        return "read";
    }

    /**
     * 创建
     * @return
     */
    public String input(){

        accessoriesFileId="";
        loginUser = usersService.getLoginInfo();

        if (StringUtils.isNotEmpty(keyId)){
            records = recordsService.get(keyId);
            if(records.getAccessories().size()>0){
                for(FileManage r:records.getAccessories()){
                    accessoriesFileId+=r.getId()+",";
                }
            }
            creater=loginUser.getName();
            createDate= DataUtil.DateToString(records.getCreateDate(),"yyyy-MM-dd");

        }else {
            creater=loginUser.getName();
            createDate= DataUtil.DateToString(new Date(),"yyyy-MM-dd");
        }

        return "input";
    }

    /**
     * 操作
     * @return
     */
    private void setData() {


        Set<FileManage> accessoriesFile= Sets.newHashSet();
        if (StringUtils.isNotEmpty(keyId)) {
            records = recordsService.get(keyId);
        } else {
            records = new Records();
            records.setCreater(usersService.getLoginInfo());
        }
        if(StringUtils.isNotEmpty(accessoriesId)){
            for (String id:accessoriesId.split(",")){
                accessoriesFile.add(fileManageService.get(id.trim()));
            }

        }
        if(StringUtils.isNotEmpty(parentId)){
            employees=employeesService.get(parentId);
            records.setEmployees(employees);
        }
        records.setCompany(usersService.getLoginInfo().getCompany());
        records.setTypes(types);
        records.setRpDate(rpDate);
        records.setAccessoriesText(accessoriesText);
        records.setAccessories(accessoriesFile);
        records.setName(name);


    }

    /**
     * 保存
     * @return
     */
    public String save(){
        setData();
        try {
            if(StringUtils.isNotEmpty(keyId)){
                recordsService.update(records);
            } else {
                Map<String, Object> various = new HashMap<String, Object>();
                various.put("numStatus", 0);
                various.put("initDuty", curDutyId);
                recordsService.save(records, "records", various);
            }
        } catch (DutyNotExistsException e) {
            return ajaxHtmlCallback("404", "当前人员无新建权限，请联系管理员！", "操作状态");
        } catch (PcfgNotExistException e) {
            return ajaxHtmlCallback("404", "找不到流程节点配置，请联系管理员！", "操作状态");
        }

        return ajaxHtmlCallback("200", "保存成功！", "操作状态");
    }

    /**
     * 提交
     * @return
     */
    public String commit(){
        setData();
        Map<String, Object> var1 = new HashMap<String, Object>();
        var1.put("numStatus", 0);
        var1.put("curDutyId", curDutyId);
        var1.put("initDuty", curDutyId);
        Map<String, Object> var2 = new HashMap<String, Object>();
        var2.put("numStatus", 1);
        var2.put("curDutyId", curDutyId);

        if(StringUtils.isEmpty(comment)){
            comment="";
        }
        try {
            if (StringUtils.isNotEmpty(keyId)) {
                recordsService.approve(records, FlowEnum.ProcessState.Finished, var2, curDutyId,comment);
            } else {
                recordsService.commit(records, FlowEnum.ProcessState.Finished,"records", var1,var2, curDutyId);

            }
        } catch (DutyNotExistsException e) {
            return ajaxHtmlCallback("404", "当前人员无新建权限，请联系管理员！", "操作状态");
        } catch (PcfgNotExistException e) {
            return ajaxHtmlCallback("404", "找不到流程节点配置，请联系管理员！", "操作状态");
        }

        return ajaxHtmlCallback("200", "提交成功！", "操作状态");
    }



    public Records getRecords() {
        return records;
    }

    public void setRecords(Records records) {
        this.records = records;
    }

    public Users getLoginUser() {
        return loginUser;
    }

    public void setLoginUser(Users loginUser) {
        this.loginUser = loginUser;
    }

    public String getTypes() {
        return types;
    }

    public void setTypes(String types) {
        this.types = types;
    }

    public Date getRpDate() {
        return rpDate;
    }

    public void setRpDate(Date rpDate) {
        this.rpDate = rpDate;
    }

    public String getAccessoriesText() {
        return accessoriesText;
    }

    public void setAccessoriesText(String accessoriesText) {
        this.accessoriesText = accessoriesText;
    }

    public String getAccessoriesFileId() {
        return accessoriesFileId;
    }

    public void setAccessoriesFileId(String accessoriesFileId) {
        this.accessoriesFileId = accessoriesFileId;
    }

    public String getCreater() {
        return creater;
    }

    public void setCreater(String creater) {
        this.creater = creater;
    }

    public String getCreateDate() {
        return createDate;
    }

    public void setCreateDate(String createDate) {
        this.createDate = createDate;
    }

    public String getAccessoriesId() {
        return accessoriesId;
    }

    public void setAccessoriesId(String accessoriesId) {
        this.accessoriesId = accessoriesId;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Employment getEmployment() {
        return employment;
    }

    public void setEmployment(Employment employment) {
        this.employment = employment;
    }

    public Employees getEmployees() {
        return employees;
    }

    public void setEmployees(Employees employees) {
        this.employees = employees;
    }
}

